import React, {Component} from 'react';
import {Layout, Comment, List, Input, Icon, Button, Modal, message} from "antd";
import {URL, MessageBoardConstant} from "../../src/constant/Constant"

const {Header, Content, Footer} = Layout;


class MessageDetail extends Component {//留言板

    constructor(props) {
        super(props);
        this.state = {
            messageData: [{}],//留言信息,从上个页面传递过来
            index: 0,
            commentData: [{}],//评论信息，从上个页面传递过来
            leaveMessage: "",//留言输入框的内容
            commentMessage: "",//评论框的内容
            toUserId: -1,
            toNickName: "",
            commentId: "",
            visible:false
        }
    }

    showModal = (event, userId, nickName, commentId, item) => {

        this.setState({
            visible: true,
            toUserId: userId,
            toNickName: nickName,
            commentId: commentId,
            messageDataItem: item
        });
    };

    //用于提交对某用户的评论
    handleOk = (event, index) => {


        console.log("aa")
        console.log(window.localStorage.username)
        console.log(this.state.toNickName)
        const flag = this.state.toNickName === window.localStorage.username
        console.log(flag)

        //不能自己给自己留言
        if(flag){
            message.info("你不能自己评论自己");
        }else{

            const toId = this.state.toUserId;
            const url = URL.urlRoot + URL.addMessage;
            console.log(url)
            const formData = new FormData();
            formData.append('commentId', this.state.commentId);
            formData.append('fromId', window.localStorage.id);//获取当前的用户id
            formData.append('fromUser', window.localStorage.username);
            formData.append('toUser', this.state.toNickName);
            formData.append('toId', toId.toString());
            //某某A 回复 某某B ：***********
            formData.append('content', window.localStorage.username+" 回复 "+this.state.toNickName+":   "+this.state.commentMessage);
            formData.append("flag","1")
            fetch(url, {
                method: 'POST',
                body: formData,
            }).then(res => {
                return res.json();
            }).then(res => {
                if (res.code === 0) {
                    message.info("留言成功sdf");
                    this.setState({
                        commentData: res.data,//更新当前评论的列表
                    })
                }
            })
        }



        this.setState({
            visible: false,
        });
    };

    handleCancel = e => {
        this.setState({
            visible: false,
        });
    };

    /**
     *
     * @param value
     * @param flag 0 代表留言，1代表评论
     */
    handleChangeTextArea(value, flag) {

        if (flag) {//评论
            this.setState({
                commentMessage: value
            });
        } else {//留言
            this.setState({
                leaveMessage: value
            });
        }

    }

    //处理留言提交事件
    handleLeaveMessageOnClick() {
        //相当于在某人评论里继续留言
        const date = new Date();
        //toId是点击评论详情是该评论主人的信息
        const toId = this.state.messageData[this.state.index].userId;
        const url = URL.urlRoot + URL.addMessage;
        const formData = new FormData();
        //commentId为当前评论详情的commentId
        formData.append('commentId',this.state.messageData[this.state.index].commentId);
        formData.append('fromId', window.localStorage.id);//获取当前的用户id
        formData.append('fromUser', window.localStorage.username);
        //toUser为给这个条留言者
        formData.append('toUser', this.state.messageData[this.state.index].nickName);
        formData.append('toId', toId.toString());
        formData.append('content', this.state.leaveMessage);
        formData.append("flag","1")
        fetch(url, {
            method: 'POST',
            body: formData,
        }).then(res => {
            return res.json();
        }).then(res => {
            if (res.code === 0) {
                message.info("留言成功");
                this.setState({
                    commentData: res.data,
                    leaveMessage: ""
                })
            }
        })
    }


    componentWillMount() {
        const {index} = this.props.location.query;
        const {messageData} = this.props.location.state
        console.log(this.props.location.state)
        const formData = new FormData();
        formData.append('commentId', this.props.location.state[index].commentId);
        formData.append("userId", this.props.location.state[index].userId);
        fetch(URL.urlRoot + URL.getAllComment, {
            method: 'POST',
            body: formData
        }).then(res => {
            return res.json();
        }).then(res => {
            if (res.code === 0) {
                console.log(res)
                this.setState({
                    commentData: res.data
                })
            }
        })//end then

        this.setState({
            messageData: this.props.location.state,
            index: index
        });
    }

    componentWillReceiveProps(nextProps, nextContext) {

    }

    render() {

        const {messageData, index, commentData} = this.state;

        const {TextArea} = Input;
        const IconText = ({type, text, userId, nickName, commentId, item}) => (
            <span>
             <Icon
                 onClick={(event) => this.showModal(event, userId, nickName, commentId, item)}
                 type={type} style={{marginRight: 8}}
             />
                {text}
            </span>
        );


        return (
            <Layout>
                <Header style={{background: '#fff', padding: 0}}>
                    <div className="head_right">
                        <img src={require("../img/logo-whut.png")}/>
                    </div>
                </Header>
                <Content style={{margin: '1%', overflow: 'auto'}}>
                    <div style={{padding: 24, background: '#fff', height: '100%'}}>
                        <div style={{
                            height: '100%'
                        }}>
                            <div
                                id={'rightmenu'}
                                style={{
                                    width: '100%'
                                }}>
                                <h1 style={{textAlign: 'center', marginBottom: '20px'}}>技术交流</h1>

                                <Comment
                                    author={<a>{messageData[index].nickName}</a>}
                                    content={
                                        <p>
                                            {messageData[index].content}
                                        </p>
                                    }
                                    datetime={messageData[index].time}
                                />
                                <List
                                    size="small"
                                    bordered
                                    dataSource={this.state.commentData}
                                    pagination={{
                                        pageSize: 5,//总共条数
                                    }}

                                    renderItem={
                                        (item, key) => (
                                            <List.Item
                                                key={item.userId}
                                                actions={[
                                                    <IconText type="message"
                                                              text={item.msgNum}
                                                              userId={item.userId}
                                                              nickName={item.nickName}
                                                              commentId={item.commentId}
                                                              item={item}/>,
                                                ]}
                                            >
                                                <List.Item.Meta
                                                    title={
                                                        <a href={'/messageDetail'}>
                                                            留言者 :{item.nickName}</a>}
                                                    description={item.time}
                                                />
                                                {item.content}
                                            </List.Item>
                                        )}
                                />
                            </div>
                        </div>
                    </div>


                    <Modal
                        title="评论"
                        visible={this.state.visible}
                        onOk={(event) => this.handleOk(event)}
                        onCancel={this.handleCancel}
                    >
                        <TextArea
                            onBlur={(event => this.handleChangeTextArea(event.target.value, 1))}//评论
                            id={'reply'}
                            placeholder="输入内容,拖动右下角可以放大"
                            autosize={{minRows: 4, maxRows: 8}}
                        />
                    </Modal>
                </Content>

                {/*底部评论模块*/}
                <div style={{padding: 14, background: '#fff', height: '30%'}}>
                    <TextArea
                        defaultValue={""}
                        value={this.state.leaveMessage}
                        onChange={(event => this.handleChangeTextArea(event.target.value, 0))}//留言
                        placeholder="输入内容,拖动右下角可以放大"
                        autosize={{minRows: 4, maxRows: 8}}
                    />
                    <Button type={'primary'} size={"large"} htmlType={"button"}
                            onClick={event => {
                                this.handleLeaveMessageOnClick();//处理留言
                            }}
                            style={{
                                float: 'right',
                                margin: '20px 5px 0px 5px'
                            }}
                    >{"提交"}</Button>
                </div>
                <Footer style={{textAlign: 'center', color: 'white', backgroundColor: 'black'}}>
                    SmartLab Design ©2018 Powered By 武汉理工大学智能技术实验室
                </Footer>
            </Layout>
        );
    }
}

export default MessageDetail;